<!-- src/lib/components/Menu/VerticalMenuPopover.svelte -->
<script lang="ts">
	import { onMount, setContext } from 'svelte';
	import Icon from '$lib/components/Basic/Icon/Icon.svelte';
	import Scrollbar from '$lib/components/Basic/Scrollbar/Scrollbar.svelte';
	import { goto } from '$app/navigation';
	import type { Option } from '$lib/components/Basic/Popover/types';
	import MenuSnippet from './Common/MenuSnippet.svelte';
	import Divider from '$lib/components/Basic/Divider/Divider.svelte';

	const {
		options = [],
		label = 'label',
		triggerRef = $bindable(),
		onClose,
		parentItem,
		className = '',
		accordion = false
	} = $props<{
		options?: Option[];
		label?: string;
		triggerRef?: HTMLElement | null;
		onClose?: () => void;
		parentItem?: Option;
		className?: string;
		accordion?: boolean;
	}>();

	let levelExpandNames = $state<Record<number, string[]>>({ 1: [], 2: [], 3: [] });
	let selectedLeafId = $state<string | number | null>(null);
	let top = $state(0);

	// 监听触发元素变化，控制弹窗显示
	$effect(() => {
		if (triggerRef) {
			top = triggerRef.offsetTop + 40;			
		}
	});

	// 关闭弹窗并重置状态
	const closePopover = () => {
		selectedLeafId = null;
		levelExpandNames = { 1: [], 2: [], 3: [] };
		onClose?.();
	};

	// 叶子节点点击处理：跳转+关闭弹窗（非叶子节点仅展开）
	const handleMenuItemClick = (option: Option, e: Event) => {
		e.stopPropagation();
		selectedLeafId = option.id;
		// 路由跳转
		if (option.code) {
			goto(option.code);
		} else {
			goto('/home');
		}
		// 仅叶子节点关闭弹窗
		if (!option.children || option.children.length === 0) {
			closePopover();
		}
	};

	// 层级展开/折叠处理（支持手风琴模式）
	function handleLevelExpandClick(level: number, name: string, e: Event) {
		e.stopPropagation();

		if (!levelExpandNames[level]) {
			levelExpandNames[level] = [];
		}

		let next: string[];
		if (accordion) {
			// 手风琴模式：同一层级只能展开一个，且关闭子层级
			next = levelExpandNames[level].includes(name) ? [] : [name];
			Object.keys(levelExpandNames).forEach((key) => {
				const currentLevel = Number(key);
				if (currentLevel > level) {
					levelExpandNames[currentLevel] = [];
				}
			});
		} else {
			// 普通模式：支持多开/关闭单个
			next = levelExpandNames[level].includes(name)
				? levelExpandNames[level].filter((n) => n !== name)
				: [...levelExpandNames[level], name];
		}

		levelExpandNames = { ...levelExpandNames, [level]: next };
	}

	// 向公共组件提供上下文配置
	setContext('vertical-menu-context', {
		getExpandNames: (level: number) => levelExpandNames[level] || [],
		handleLevelExpandClick,
		isCollapsed: () => false // 弹窗内菜单始终不收缩
	});

	// 点击外部关闭弹窗
	onMount(() => {
		const handleClickOutside = (event: MouseEvent) => {
			if (
				triggerRef &&
				!triggerRef.contains(event.target as Node) &&
				!document.querySelector('.popover-cascader')?.contains(event.target as Node)
			) {
				closePopover();
			}
		};

		document.addEventListener('click', handleClickOutside);
		return () => {
			document.removeEventListener('click', handleClickOutside);
		};
	});
</script>

<!-- <Portal target="body">	 -->
	<div class="popover-container {className}" style="--top: {top}px;">
		<div
			class="popover-cascader"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => {
				// ESC 键关闭弹窗
				if (e.key === 'Escape') {
					e.stopPropagation();
					closePopover();
				}
			}}
			role="dialog"
			aria-modal="true"
			aria-labelledby={parentItem ? 'popover-header-title' : undefined}
			tabindex="0"
		>
			<div style="height: 100%;overflow: hidden;">
				{#if parentItem}
					<!-- 弹窗头部：显示父菜单名称 -->
					<div class="popover-header">
						<Icon src={parentItem.iconName || 'weather/moon'} size="16" style="flex-shrink: 0;" />
						<span class="header-title" id="popover-header-title">
							{parentItem[label]}
						</span>
					</div>
					<div style="padding: 0 12px;">
						<Divider style="dashed" color="color-mix(in srgb, var(--color-info-700) 20%, transparent)" margin="0px"></Divider>
					</div>
				{/if}
				{#if options && options.length > 0}
					<div class="popover-body">
						<!-- 菜单内容：引用公共 MenuSnippet 组件 -->
						<Scrollbar scrollPadding={1} innerPadding="0 1px">
							<MenuSnippet
								items={options}
								{selectedLeafId}
								onItemClick={handleMenuItemClick}
								{label}
								isCollapsed={false}
								level={1}
							/>
						</Scrollbar>
					</div>
				{/if}
			</div>
		</div>
	</div>	
<!-- </Portal> -->

<style scoped lang="scss">
	.popover-container {
		position: fixed;
		top: 0;
		left: 50px;
		width: 0;
		height: 100%;
		z-index: -1;
		outline: none;
		background-color: var(--color-page);		
		padding: 6px 6px 6px 0;
		border-radius: 0 8px 8px 0;
		transition: width 0.2s ease-in-out;
		box-shadow: 8px 0 8px -6px var(--color-shadow);
	}
	.popover-container.is-expanded {
		width: 240px;		
	}
	.popover-cascader {
		position: relative;		
		height: 100%;
		border-radius: 8px;
		background-color: var(--color-fill);
	}
	.popover-container.is-expanded .popover-cascader::after {
		content: '';
		position: absolute;
		top: var(--top);
		left: -42px;
		width: 42px;
		height: 40px;
		border-radius: 8px 0 0 8px;
		z-index: 999;
		background-color: var(--color-fill);
	}
	.popover-header {
		display: flex;
		align-items: center;
		justify-content: flex-start;	
		white-space: nowrap;		
		height: 48px;
		padding: 0 16px;
		font-weight: 500;		

		.header-title {
			margin-left: 8px;
			font-size: 14px;
			line-height: 16px;
			font-weight: 500;
			font-family: Arial, Helvetica, sans-serif;
		}
	}

	.popover-body {
		height: calc(100% - 54px);
		margin-top: 2px;
	}
</style>
